import { TranslateClient, TranslateTextCommand } from '@aws-sdk/client-translate';
import dotenv from 'dotenv';

dotenv.config();

// 创建AWS Translate客户端
const translateClient = new TranslateClient({
  region: process.env.AWS_REGION || 'us-east-1',
  credentials: {
    accessKeyId: process.env.AWS_ACCESS_KEY_ID || '',
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || ''
  }
});
console.log('AWS Translate客户端创建成功',process.env.AWS_ACCESS_KEY_ID);

/**
 * 翻译文本
 * @param text 要翻译的文本
 * @param sourceLanguage 源语言代码
 * @param targetLanguage 目标语言代码
 * @returns 翻译后的文本
 */
export const translateText = async (
  text: string,
  sourceLanguage: string,
  targetLanguage: string
): Promise<string> => {
  try {
    // 语言代码映射
    const languageCodeMap: Record<string, string> = {
      '中文': 'zh',
      '英文': 'en',
      '日文': 'ja',
      '韩文': 'ko',
      '法文': 'fr',
      '德文': 'de',
      '西班牙文': 'es',
      '俄文': 'ru',
      // 可以添加更多语言映射
    };

    // 获取标准语言代码
    const sourceCode = languageCodeMap[sourceLanguage] || sourceLanguage;
    const targetCode = languageCodeMap[targetLanguage] || targetLanguage;

    const command = new TranslateTextCommand({
      Text: text,
      SourceLanguageCode: sourceCode,
      TargetLanguageCode: targetCode
    });

    const response = await translateClient.send(command);
    return response.TranslatedText || text;
  } catch (error) {
    console.error('翻译服务错误:', error);
    throw error;
  }
};